using System;
using System.Windows;
using System.Windows.Controls;

namespace ibba.src.sl.recursos.Validations
{
	using System.Text.RegularExpressions;

	public class RegexValidation : ValidationBase
	{
		public RegexValidation()
			: base()
		{
		}
	
		public Regex RegExpression
		{
			get { return (Regex)GetValue(RegExpressionProperty); }
			set { SetValue(RegExpressionProperty, value); }
		}
		// Using a DependencyProperty as the backing store for RegExpression.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty RegExpressionProperty =
			DependencyProperty.Register("RegExpression", typeof(Regex), typeof(RegexValidation), new PropertyMetadata(null));
			
		public string Expression
		{
			get { return (string)GetValue(ExpressionProperty); }
			set { SetValue(ExpressionProperty, value); }
		}
		// Using a DependencyProperty as the backing store for Expression.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty ExpressionProperty =
			DependencyProperty.Register("Expression", typeof(string), typeof(RegexValidation), new PropertyMetadata(ExpressionPropertyChangedCallback));

		public static void ExpressionPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			try
			{
				d.SetValue(RegExpressionProperty, 
					new Regex(e.NewValue.ToString()));
			}
			catch{
				d.SetValue(RegExpressionProperty, null);
			}
		}
		

		protected override bool ValidateControl()
		{
			if (ElementToValidate is TextBox && RegExpression!=null)
			{
				TextBox box = ElementToValidate as TextBox;
				if(String.IsNullOrEmpty(box.Text)) return true;

				return RegExpression.Match(box.Text).Success;
			}
			return true;
		}
	}
}
